/**
 * 
 */
package soa.security.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.ldap.query.ContainerCriteria;
import org.springframework.ldap.query.SearchScope;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Repository;

import soa.security.dao.PositionDao;
import soa.security.domain.Person;
import soa.security.domain.Position;

/**
 * @author Cre.Gu
 *
 */
@Repository
public class PositionDaoImpl extends SpringLdapDaoImpl<Position> implements
		PositionDao {

	@Override
	public void create(Position t) {
		t.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		ldapTemplate.create(t);

	}

	@Override
	public Position findByDn(String dn) {
		Position o = ldapTemplate.findByDn(LdapNameBuilder.newInstance(dn)
				.build(), Position.class);
		o.setBid(LdapUtils.getStringValue(o.getDn(), o.getDn().size() - 1));
		o.setOrganization(unitBelongs(dn));
		return o;
	}

	@Override
	public List<Position> allPositions(String baseDn, SearchScope searchScope,
			Map<String, Object> parameters) {
		ContainerCriteria query = baseQuery(baseDn, searchScope);

		buildLikeCriteria(query, parameters, "cname");
		buildLikeCriteria(query, parameters, "duty");
		buildEqualsCriteria(query, parameters, "dutyType");
		buildEqualsCriteria(query, parameters, "dutyLevel");

		return ldapTemplate.search(query, new BaseContextMapper());
	}

	@Override
	public void addPersons(Position position, Person person) {
		addAttrName(position.getDn(), "persons", person.getDn().toString());
	}

	@Override
	public void removePersons(Position position, Person person) {
		removeAttrName(position.getDn(), "persons", person.getDn().toString());
	}

	@Override
	public List<String> allPersons(Position position) {
		return allAttrName(position.getDn(), "persons");
	}

	@Override
	public String getObjectClass() {
		return "zjtzsw-position";
	}
}
